package edu.purdue.rcac.cesm.interceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.security.sasl.AuthenticationException;

import org.apache.log4j.Logger;
import org.jboss.mx.util.MBeanProxyExt;
import org.jboss.mx.util.MBeanServerLocator;

import edu.purdue.rcac.service.dispatch.ServiceDispatcherManagement;

public class AuthenticateInterceptor {
	protected static final Logger logger = Logger.getLogger(AuthenticateInterceptor.class.getName());
	private static ServiceDispatcherManagement serviceDispatcher;
	
	static {
		MBeanServer server = MBeanServerLocator.locateJBoss();
		try {
			// serviceDispatcher initialization: MBean object name look up
			logger.info("Look up object name: "
					+ ServiceDispatcherManagement.OBJECT_NAME);
			serviceDispatcher = (ServiceDispatcherManagement) MBeanProxyExt
					.create(ServiceDispatcherManagement.class,
							ServiceDispatcherManagement.OBJECT_NAME, server);
		} catch (MalformedObjectNameException e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	@AroundInvoke
	public Object validate(InvocationContext ctx) throws Exception{
		String methodName = ctx.getMethod().getName();
		Object[] params = ctx.getParameters();
		String userName = params[0].toString();
		String token = params[params.length-1].toString();
		System.out.println("INTERCEPT "+methodName);
		System.out.println("USERNAME: "+userName);
		System.out.println("TOKEN: "+token);
		
		if (!serviceDispatcher.verifyToken(userName, token)){
			throw new AuthenticationException("invalid username/token, please renew your token and continue");
		}
		
		if (token.equals("")){
			throw new AuthenticationException("token is required for authentication");
		}
		return ctx.proceed();
	}
}
